package com.sgcc.pms.api.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sgcc.pms.api.domain.MxpmsSearchEquipment;
import com.sgcc.pms.api.repository.MxpmsSearchEquipmentRepository;
import com.sgcc.pms.api.service.dto.MxpmsSearchEquipmentDTO;
import com.sgcc.pms.api.service.mapper.MxpmsSearchEquipmentMapper;
import com.sgcc.pms.api.web.rest.util.HeaderUtil;
import com.sgcc.pms.api.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import io.swagger.annotations.ApiParam;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing MxpmsSearchEquipment.
 */
@RestController
@RequestMapping("/api")
public class MxpmsSearchEquipmentResource {
    private static final CloseableHttpClient httpClient;

    private final Logger log = LoggerFactory.getLogger(MxpmsSearchEquipmentResource.class);

    private static final String ENTITY_NAME = "mxpmsSearchEquipment";

    private final MxpmsSearchEquipmentRepository mxpmsSearchEquipmentRepository;

    private final MxpmsSearchEquipmentMapper mxpmsSearchEquipmentMapper;

    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    public MxpmsSearchEquipmentResource(MxpmsSearchEquipmentRepository mxpmsSearchEquipmentRepository, MxpmsSearchEquipmentMapper mxpmsSearchEquipmentMapper) {
        this.mxpmsSearchEquipmentRepository = mxpmsSearchEquipmentRepository;
        this.mxpmsSearchEquipmentMapper = mxpmsSearchEquipmentMapper;
    }

    /**
     * POST  /mxpms-search-equipments : Create a new mxpmsSearchEquipment.
     *
     * @param mxpmsSearchEquipmentDTO the mxpmsSearchEquipmentDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new mxpmsSearchEquipmentDTO, or with status 400 (Bad Request) if the mxpmsSearchEquipment has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/mxpms-search-equipments")
    @Timed
    public ResponseEntity<MxpmsSearchEquipmentDTO> createMxpmsSearchEquipment(@RequestBody MxpmsSearchEquipmentDTO mxpmsSearchEquipmentDTO) throws URISyntaxException {
        log.debug("REST request to save MxpmsSearchEquipment : {}", mxpmsSearchEquipmentDTO);
        if (mxpmsSearchEquipmentDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new mxpmsSearchEquipment cannot already have an ID")).body(null);
        }
        MxpmsSearchEquipment mxpmsSearchEquipment = mxpmsSearchEquipmentMapper.toEntity(mxpmsSearchEquipmentDTO);
        mxpmsSearchEquipment = mxpmsSearchEquipmentRepository.save(mxpmsSearchEquipment);
        MxpmsSearchEquipmentDTO result = mxpmsSearchEquipmentMapper.toDto(mxpmsSearchEquipment);
        return ResponseEntity.created(new URI("/api/mxpms-search-equipments/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /mxpms-search-equipments : Updates an existing mxpmsSearchEquipment.
     *
     * @param mxpmsSearchEquipmentDTO the mxpmsSearchEquipmentDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated mxpmsSearchEquipmentDTO,
     * or with status 400 (Bad Request) if the mxpmsSearchEquipmentDTO is not valid,
     * or with status 500 (Internal Server Error) if the mxpmsSearchEquipmentDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/mxpms-search-equipments")
    @Timed
    public ResponseEntity<MxpmsSearchEquipmentDTO> updateMxpmsSearchEquipment(@RequestBody MxpmsSearchEquipmentDTO mxpmsSearchEquipmentDTO) throws URISyntaxException {
        log.debug("REST request to update MxpmsSearchEquipment : {}", mxpmsSearchEquipmentDTO);
        if (mxpmsSearchEquipmentDTO.getId() == null) {
            return createMxpmsSearchEquipment(mxpmsSearchEquipmentDTO);
        }
        MxpmsSearchEquipment mxpmsSearchEquipment = mxpmsSearchEquipmentMapper.toEntity(mxpmsSearchEquipmentDTO);
        mxpmsSearchEquipment = mxpmsSearchEquipmentRepository.save(mxpmsSearchEquipment);
        MxpmsSearchEquipmentDTO result = mxpmsSearchEquipmentMapper.toDto(mxpmsSearchEquipment);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, mxpmsSearchEquipmentDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /mxpms-search-equipments : get all the mxpmsSearchEquipments.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of mxpmsSearchEquipments in body
     */
    @GetMapping("/mxpms-search-equipments")
    @Timed
    public ResponseEntity<List<MxpmsSearchEquipmentDTO>> getAllMxpmsSearchEquipments(@ApiParam Pageable pageable) {
        log.debug("REST request to get a page of MxpmsSearchEquipments");
        Page<MxpmsSearchEquipment> page = mxpmsSearchEquipmentRepository.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/mxpms-search-equipments");
        return new ResponseEntity<>(mxpmsSearchEquipmentMapper.toDto(page.getContent()), headers, HttpStatus.OK);
    }

    /**
     * GET  /mxpms-search-equipments/:id : get the "id" mxpmsSearchEquipment.
     *
     * @param id the id of the mxpmsSearchEquipmentDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the mxpmsSearchEquipmentDTO, or with status 404 (Not Found)
     */
    @GetMapping("/mxpms-search-equipments/{id}")
    @Timed
    public ResponseEntity<MxpmsSearchEquipmentDTO> getMxpmsSearchEquipment(@PathVariable Long id) {
        log.debug("REST request to get MxpmsSearchEquipment : {}", id);
        MxpmsSearchEquipment mxpmsSearchEquipment = mxpmsSearchEquipmentRepository.findOne(id);
        MxpmsSearchEquipmentDTO mxpmsSearchEquipmentDTO = mxpmsSearchEquipmentMapper.toDto(mxpmsSearchEquipment);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(mxpmsSearchEquipmentDTO));
    }

    /**
     * DELETE  /mxpms-search-equipments/:id : delete the "id" mxpmsSearchEquipment.
     *
     * @param id the id of the mxpmsSearchEquipmentDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/mxpms-search-equipments/{id}")
    @Timed
    public ResponseEntity<Void> deleteMxpmsSearchEquipment(@PathVariable Long id) {
        log.debug("REST request to delete MxpmsSearchEquipment : {}", id);
        mxpmsSearchEquipmentRepository.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * 搜索索引
     * @param params
     * @return
     */
    @PostMapping("/v3/searchIndex")
    @Timed
    public String searchIndexV3(String params,@RequestBody String body) throws JsonParseException,IOException {
        // http://www.baeldung.com/httpclient-post-http-request
        // https://my.oschina.net/u/1270482/blog/212389
        String result = null;
        List<MxpmsSearchEquipment> resultList = new ArrayList<MxpmsSearchEquipment>(); // 结果id集合
        String index = "equipment/unit";
        String url = "http://172.16.221.59:19200/" + index + "/_search";
        JSONObject json = new JSONObject();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(body);
        HttpPost httpPost = new HttpPost(url);
        StringEntity stringEntity = new StringEntity(body);
        stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if(HttpStatus.OK.value() == statusCode){
                HttpEntity entity = response.getEntity();
                if (entity != null){
                    result = EntityUtils.toString(entity, "utf-8");
                    log.info("result="+result);
                }
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            response.close();
        }
        return result;
    }

    @PostMapping("/v4/searchIndex")
    @Timed
    public String searchIndexV4(String params,@RequestBody String body) throws JsonParseException,IOException {
        // http://www.baeldung.com/httpclient-post-http-request
        // https://my.oschina.net/u/1270482/blog/212389
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");

        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");

        System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "debug");

        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");

        String result = null;
        List<MxpmsSearchEquipment> resultList = new ArrayList<MxpmsSearchEquipment>(); // 结果id集合

//      String url = "http://127.0.0.1:9200/_sql?sql=select%20*%20from%20equipment%20limit%203";
        String ual = "http://127.0.0.1:9200/_sql?sql=select%20*%20from%20equipment%20limit%203";
        String query = "select * from equipment limit 3";
        String url = "http://127.0.0.1:9200/_sql?sql="+java.net.URLEncoder.encode(query, "UTF-8").replace("+", "%20");
        log.info("url="+url);
        JSONObject json = new JSONObject();
        ObjectMapper mapper = new ObjectMapper();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if(HttpStatus.OK.value() == statusCode){
                HttpEntity entity = response.getEntity();
                if (entity != null){
                    result = EntityUtils.toString(entity, "utf-8");
                    log.info("result="+result);
                }
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            response.close();
        }
        return result;
    }
}
